$(function () {
  // 面包屑导航
  function nav() {
    let element = layui.element
    element.init($('.x-nav').html(`
    <span class="layui-breadcrumb">
      <a href="">首页</a>
      <a href="">分类管理</a>
      <a><cite>正文</cite></a>
    </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:5px;float:right" onclick="location.reload()" title="刷新">
    <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i>
    </a>
    `))
  }
  nav()

  let form = layui.form

  // PART ============== 渲染页面 ==============

  // 获取本地token令牌
  let token = localStorage.getItem('x-token')

  let querydata = {
    "catename": '',
    "page": '1',  // 当前页码
    "limit": '10',  // 每页数量
    "x-token": token
  }
  // 封装渲染函数
  async function getRender(flage) {
    try {
      // 发送axios请求获取数据
      const { data: { data } } = await axios.get('/ydd_cate/list', {
        params: querydata
      })

      // 判断数据是否为空
      if (data.data.length === 0) {
        layer.msg('没有相关数据数据')
      }
      $('tbody').html(data.data.map((item, index) => {
        const { catename, icon, id, sort_num, } = item
        return `
        <tr>
          <td>${index + 1}</td>
          <td>${id}</td>
          <td>${catename}</td>
          <td>${icon} &nbsp <i class="bqicon fa ${icon}"></i></td>
          <td>${sort_num}</td>
          <td class="handle">
            <a class="edit" href="javascript:;" data-id=${id}>
              <i class="handle-icon layui-icon layui-icon-util"></i>
            </a>
            <a class="delet" href="javascript:;" data-id=${id}>
              <i class="handle-icon layui-icon layui-icon-delete"></i>
            </a>
          </td>
        </tr>
        `
      }).join(''))
      renderPage(data.count)
    } catch (error) {
      layer.msg('数据获取失败')
    }
  }
  // 渲染页面
  getRender()

  // PART ============== 添加分类 ==============

  // 添加按钮弹出层样式
  let addFormstr = `
  <form id="addForm" class="layui-form">
    <!-- 第一行 分类名称 -->
    <div class="layui-form-item addForminput">
      <label class="layui-form-label">分类名称</label>
      <div class="layui-input-block">
        <input type="text" name="catename" required lay-verify="required" placeholder="请输入分类名" autocomplete="off"
          class="layui-input">
      </div>
    </div>
    <!-- 第二行 图标class  -->
    <div class="layui-form-item addForminput">
      <label class="layui-form-label">图标class</label>
      <div class="layui-input-block">
        <input type="text" name="icon" required lay-verify="required" placeholder="请输入class名" autocomplete="off"
          class="layui-input">
        <span><a href="https://fontawesome.com.cn/v4/icons-ui/">具体参见fontawesome图标库</a></span>
      </div>
    </div>
    <!-- 第三行 排序大小 -->
    <div class="layui-form-item addForminput">
      <label class="layui-form-label">排序大小</label>
      <button type="button" class="subnum layui-btn layui-btn-sm">-</button>
      <input type="text" name="sort_num" lay-verify="required" value="10" layui-disabled autocomplete="off"
          class="layui-input">
      <button type="button" class="addnum layui-btn layui-btn-sm">+</button>
    </div>
    <!-- 按钮 -->
    <div class="layui-form-item">
      <div class="layui-input-block subbtn">
        <button type="button" id="callOff" class="layui-btn layui-bg-gray">取消</button>
        <button id="ss" lay-submit class="layui-btn">确定</button>
      </div>
    </div>
  </form>
  `

  // let cateAdddata = {
  //   "catename": ""
  // }

  // 弹出层加减
  $('body').on('click', '.subnum', function () {
    $('[name=sort_num]').val(+$('[name=sort_num]').val() - 1)
  })
  $('body').on('click', '.addnum', function () {
    $('[name=sort_num]').val(+$('[name=sort_num]').val() + 1)
  })

  // 给新增按钮绑定点击事件
  let cateAddForm
  $('#addbtn').on('click', function () {
    // 使用layui实现弹出层
    cateAddForm = layer.open({
      content: addFormstr,
      type: 1,
      title: '添加分类',
      area: ['600px', '346px'],
      skin: 'layui-layer-lan',
      offset: ['160px']
    })
  })



  // 给取消按钮绑定关闭弹出层功能
  $('body').on('click', '#callOff', function () {
    layer.close(cateAddForm)
  })

  $('body').on('submit', '#addForm', async function (e) {
    e.preventDefault()
    const formdata = $(this).serialize()

    try {
      const add = await axios.post('/ydd_cate/add', formdata)
      // console.log(add)
      getRender()
      layer.close(cateAddForm)
      layer.msg('数据添加成功')
    } catch (error) {
      layer.msg('数据获取失败')
    }
  })

  // PART ============== 编辑分类 ==============

  // 编辑按钮弹出层样式
  let editFormstr = `
  <form id="editForm" class="layui-form" lay-filter="editText">
    <!-- 第一行 分类id -->
    <div class="layui-form-item" id="ids">
      <label class="layui-form-label">id</label>
      <div class="layui-input-block">
        <input type="text" name="id" required lay-verify="required" placeholder="请输入id" autocomplete="off"
          class="layui-input">
      </div>
    </div>
    <!-- 第二行 分类名称 -->
    <div class="layui-form-item addForminput">
      <label class="layui-form-label">分类名称</label>
      <div class="layui-input-block">
        <input type="text" name="catename" required lay-verify="required" placeholder="请输入分类名" autocomplete="off"
          class="layui-input">
      </div>
    </div>
    <!-- 第三行 图标class  -->
    <div class="layui-form-item addForminput">
      <label class="layui-form-label">图标class</label>
      <div class="layui-input-block">
        <input type="text" name="icon" required lay-verify="required" placeholder="请输入class名" autocomplete="off"
          class="layui-input">
        <span><a href="https://fontawesome.com.cn/v4/icons-ui/">具体参见fontawesome图标库</a></span>
      </div>
    </div>
    <!-- 第四行 排序大小 -->
    <div class="layui-form-item addForminput">
      <label class="layui-form-label">排序大小</label>
      <button type="button" class="subnum layui-btn layui-btn-sm">-</button>
      <input type="text" name="sort_num" lay-verify="required" value="10" layui-disabled autocomplete="off"
          class="layui-input">
      <button type="button" class="addnum layui-btn layui-btn-sm">+</button>
    </div>
    <!-- 按钮 -->
    <div class="layui-form-item">
      <div class="layui-input-block subbtn">
        <button type="button" id="callOff1" class="layui-btn layui-bg-gray">取消</button>
        <button lay-submit class="layui-btn">确定</button>
      </div>
    </div>
  </form>
  `

  let cateEditForm
  $('body').on('click', '.handle .edit', function () {
    // 使用layui实现弹出层
    cateEditForm = layer.open({
      content: editFormstr,
      type: 1,
      title: '编辑分类',
      area: ['600px', '346px'],
      skin: 'layui-layer-molv',
      offset: ['140px']
    })

    $('body').on('click', '#callOff1', function () {
      layer.close(cateEditForm)
    })

    const id = $(this).attr("data-id")

    // 获取数据给表单赋值
    async function getEdit() {
      try {
        const { data: { data: { id: ids, catename, icon, sort_num } } } = await axios.get('/ydd_cate/rowInfo', {
          params: {
            id,
            token
          }
        })
        //给表单赋值
        //formedit 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
        form.val("editText", {
          "id": ids,
          "catename": catename,
          "icon": icon,
          "sort_num": sort_num
        })
      } catch (error) {
        console.log(error)
      }
    }
    getEdit()
  })

  // 给编辑按钮弹出层绑定提交事件
  $('body').on('submit', '#editForm', function (e) {
    e.preventDefault()
    // 获取表单数据发送请求修改数据
    async function setEdit() {
      try {
        const data = $('#editForm').serialize()
        const axiosedit = await axios.post('/ydd_cate/update', data)
        layer.msg('数据修改成功')
        getRender()
        layer.close(cateEditForm)
      } catch (error) {
        console.log(error)
      }
    }
    setEdit()
  })

  // PART ============== 删除分类 ==============
  $('body').on('click', '.handle .delet', async function () {
    const id = $(this).attr("data-id")
    try {
      const res = await axios.get('/ydd_cate/del', {
        params: {
          id,
          token
        }
      })
      layer.msg('数据删除成功')
      getRender()
    } catch (error) {
      console.log(error)
    }
  })

  // PART ============== 筛选分类 ==============

  $('.screen').on('click', async function (e) {
    e.preventDefault()
    const data = $('#nameinput').val()
    querydata.catename = data
    const flage = true
    getRender(flage)
    $('#screenForm [type="reset"]').click()
  })

  // PART ============== 分页 ==============

  function renderPage(count) {
    var laypage = layui.laypage;
    //执行一个laypage实例
    laypage.render({
      elem: 'pagebox', //注意，这里的 test1 是 ID，不用加 # 号
      count: count, //数据总数，从服务端得到
      limit: querydata.limit,
      curr: querydata.page,
      layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
      limits: [1, 2, 3, 5, 10],
      // laypage.render 函数调用或分页切换时触发 jump
      // 如果是laypage.render 函数触发 first 是 true
      // 分页切换时触发 first 是 undefined
      jump: function (obj, first) {
        // querydata.page = obj.curr
        // getRender()
        if (!first) {
          querydata.page = obj.curr
          querydata.limit = obj.limit
          getRender()
        }
      }
    })
  }

  // PART ============== 全部数据 ==============

  async function getbothRender() {
    try {
      // 发送axios请求获取数据
      const { data: { data } } = await axios.get('/ydd_cate/all', {
        params: {
          "x-token": token
        }
      })
      // console.log(data)
      $('.exportTable').html(data.map((item, index) => {
        const { catename, icon, id, sort_num, } = item
        return `
        <tr>
          <td>${index + 1}</td>
          <td>${id}</td>
          <td>${catename}</td>
          <td>${icon} &nbsp <i class="bqicon fa ${icon}"></i></td>
          <td>${sort_num}</td>
          <td class="handle">
            <a class="edit" href="javascript:;" data-id=${id}>
              <i class="handle-icon layui-icon layui-icon-util"></i>
            </a>
            <a class="delet" href="javascript:;" data-id=${id}>
              <i class="handle-icon layui-icon layui-icon-delete"></i>
            </a>
          </td>
        </tr>
        `
      }).join(''))
    } catch (error) {
      layer.msg('数据获取失败')
    }
  }

  getbothRender()

  // PART ============== 导出数据 ==============

  $('#exportbtn').on('click', function () {
    var blob = new Blob([document.getElementsByClassName("exportTable")[0].outerHTML], {
      type: "text/plain;charset=utf-8"
    })
    saveAs(blob, "export.xls")
  })
})